﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;

using WoodRobotics.PasswordKeeper.ViewModel;
using System.Windows.Threading;
using System.Threading;

namespace WoodRobotics.PasswordKeeper
{
    
    public partial class MainUI : Window
    {
        
        #region Constructor 
        public MainUI()
        {
            InitializeComponent();
        }
        #endregion
        
        #region Fields
        private Passwords m_Passwords;
        #endregion
        
        #region Events
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            m_Passwords = new Passwords();
            m_Passwords.EncryptUpdated += new EventHandler(m_Passwords_EncryptUpdated);
            this.DataContext = m_Passwords;
        }

        private void m_Passwords_EncryptUpdated(object sender, EventArgs e)
        {
            dataGrid1.Items.Refresh();
        }
        private void cmdConnect_Click(object sender, RoutedEventArgs e)
        {
            Connect();
        }
        private void cmdLogout_Click(object sender, RoutedEventArgs e)
        {
            m_Passwords.Disconnect();
            ((StatusBarItem)stbStatus.Items[0]).Content = "Status: Not Connected";
        }
        private void txtPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                Connect();
        }
        #endregion
        
        #region Methods 
        private void Connect()
        {
            ((StatusBarItem)stbStatus.Items[0]).Content = "Status: Connecting ...";
            DoEvents();

            m_Passwords.Connect();

            if (m_Passwords.IsConnected)
            {
                ((StatusBarItem)stbStatus.Items[0]).Content = "Status: Connected";
                passwordBox1.Focus();
            }
            else
                ((StatusBarItem)stbStatus.Items[0]).Content = "Status: Connection Failed!";
        }
        
        private void DoEvents()
        {
            DispatcherFrame frame = new DispatcherFrame(true);
            Dispatcher.CurrentDispatcher.BeginInvoke
            (
                DispatcherPriority.Background,
                (SendOrPostCallback)delegate(object arg)
                {
                    var f = arg as DispatcherFrame;
                    f.Continue = false;
                },
                frame
            );
            Dispatcher.PushFrame(frame);
        }
        #endregion
        
    }
    
}
